<?php
namespace Plu\qdh\Controllers\Api;
use Plu\qdh\Controllers\Api\ControllerBase;
use Plu\qdh\Services\OrderService;
use Plu\qdh\Services\ProductService;
use Plu\qdh\Services\PaymentService;

/**
 * @RoutePrefix("/order")
 */
class OrderController extends ControllerBase {


    /**
	 * @Get('/saveOrder')
	 * 保存订单
	 */
    public function saveOrderAction() {

        $userId = $this->passport->isLogin();
	
	    if (!$userId) {
            return $this->needLogin();
        }

        $productNo = $this->request->getQuery('productNo');
        $linkMan   = $this->request->getQuery('linkMan');
        $linkPhone = $this->request->getQuery('linkPhone');
        $travelDay = $this->request->getQuery('travelDay');
        $num       = $this->request->getQuery('num');
        $custId    = $this->request->getQuery('custid');

        if (!$productNo || !$linkMan || !$linkPhone || !$travelDay || !$num) {
            return $this->missParams();
        }

        $service   = new OrderService;
        $service->setProductNo($productNo);
        $service->setTravateData($travelDay);
        $saveOrder = $service->saveOrder($linkMan, $linkPhone, $num, $custId);
        return $this->release($saveOrder);
    }

    /**
	 * @Get('/getOrderDetail')
	 * 订单详情
	 */
    public function getOrderDetailAction() {

        $userId = $this->passport->isLogin();
        if (!$userId) {
           return $this->needLogin();
       }

        $orderId = $this->request->getQuery('orderId');

        if (!$orderId) {
            return $this->missParams();
        }

        $service   = new OrderService;
        $service->setOrderId($orderId);
        $orderDetail = $service->getOrderDetail($orderId);
        if (!empty($orderDetail)) {
     	    $code = 200;
	    } else {
	        $code = 201;
	    }
        return $this->release([
            'code' => $code,
            'items' => $orderDetail
        ]);

    }

    /**
	 * @Get('/myOrders')
	 * 订单详情
	 */
    public function myOrdersAction() {
        $userId = $this->passport->isLogin();
        if (!$userId) {
            return $this->needLogin();
        }
    	$status    = $this->request->getQuery('status', 'int', 1);
        $page      = $this->request->getQuery('page', 'int', 1);
        $limit     = 10;
        $offset    = ($page - 1) * $limit;
        $service   = new OrderService;
        list($count, $items)  = $service->getUserOrders($limit, $offset, $status);
        return $this->release([
            'code'    => 200,
	        'current' => $page,
            'total'   => $count,
            'items'   => $items
        ]);
    }

    /**
	 * @Get('/cancelOrder')
	 * 取消订单
	 */
    public function cancelOrderAction() {

        $userId = $this->passport->isLogin();
        if (!$userId) {
            return $this->needLogin();
        }

        $orderId = $this->request->getQuery('orderId');
        $service = new OrderService;
        $cancel  = $service->cancelOrder($orderId);
        return $this->release($cancel);
    }

    /**
	 * @Get('/initPayment')
	 * 生成支付签名
	 */
    public function initPaymentAction() {
        
        $orderId = $this->request->getQuery('orderId');

        $userId = $this->passport->isLogin();
        
        if (!$userId) {
                return $this->needLogin();
            }

            if (!$orderId) {
                return $this->missParams();
            }

            $orderService   = new OrderService;
            $orderInfo = $orderService->getOrderDetail($orderId);
            

        if (empty($orderInfo)) {
                return [
                    'code' => \OrderConst::API_ORDER_STATUS['missing'],
                    'msg'  => '订单不存在'
                ];
            }

        if ($orderInfo['orderAccount'] != $userId) {
            return [
                'code' => \OrderConst::API_ORDER_STATUS['permission'],
                'msg'  => '无权操作'
            ];
        }

       $payMinute = $orderInfo['payMinute'];
       $timeLeft  = $orderInfo['createTime'] - time();
       if ($timeLeft > $payMinute) {
           return [
               'code' => \OrderConst::API_ORDER_STATUS['expire'],
               'msg'  => '已过支付有效期，请重新下单'
           ];
       }

        $paymentService = new PaymentService;

        $paymentService->setOrderId($orderId);
        
	    $initPayment = $paymentService->initPayment();

        return $this->release($initPayment);

    }

    /**
	 * @Post('/afterPayment')
	 * 微信回调
	 */
    public function afterPaymentAction() {

	    $postXml  = file_get_contents("php://input");
        
        $jsonxml  = json_encode(simplexml_load_string($postXml, 'SimpleXMLElement', LIBXML_NOCDATA));

        $paymentService = new PaymentService;
        
        $afterPayment   = $paymentService->afterPayment($jsonxml);

        if ($afterPayment) {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            echo '<xml><return_code><![CDATA[ERROR]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
        }
        exit;
    }

    /**
	 * @Post('/orderCreateNotify')
	 * 第三方出票回调
	 */
    public function orderNotifyAction() {
        $postXml   = file_get_contents("php://input");
        $postArr   = explode("&", $postXml);
        $orderArr  = $postArr[2];
        $orderInfo = explode("=", $orderArr);
        $orderId   = $orderInfo[1];
        $this->logger->log('订单出票 orderId='.$orderId);
        $service  = new OrderService;
        $service->publishOrder($orderId);

        header("Content-type:text/xml;charset=utf-8");
        echo '<?xml version="1.0" encoding="UTF-8"?><root><result>true</result><msg>接收成功</msg></root>';
        exit;
    }

    /**
	 * @Post('/orderCancelNotify')
	 * 第三方取消订单回调
	 */
    public function orderCancelNotifyAction() {
        $postXml   = file_get_contents("php://input");
        $postArr   = explode("&", $postXml);
        $orderArr  = $postArr[2];
        $orderInfo = explode("=", $orderArr);
        $orderId   = $orderInfo[1];
        $this->logger->log('订单取消 orderId='.$orderId);
        $service   = new OrderService;
        $service->notifyCancelOrder($orderId);

        header("Content-type:text/xml;charset=utf-8");
        echo '<?xml version="1.0" encoding="UTF-8"?><root><result>true</result><msg>接收成功</msg></root>';
        exit;
    }


    /**
	 * @Post('/orderUsedNotify')
	 * 核销通知
	 */
    public function orderUsedlNotifyAction() {
        $postXml   = file_get_contents("php://input");
        $postArr   = explode("&", $postXml);
        $testData  = json_encode($postArr);
        $orderArr  = $postArr[2];
        $orderInfo = explode("=", $orderArr);
        $orderId   = $orderInfo[1];

        $this->logger->log('核销通知'.$testData);

        $service   = new OrderService;
        $service->usedOrder($orderId);

        header("Content-type:text/xml;charset=utf-8");
        echo '<?xml version="1.0" encoding="UTF-8"?><root><result>true</result><msg>接收成功</msg></root>';
        exit;

    }

    /**
	 * @Post('/orderRefindNotify')
	 * 退改通知
	 */
    public function orderRefindNotifyAction() {
        $postXml   = file_get_contents("php://input");
        $postArr   = explode("&", $postXml);
        $testData  = json_encode($postArr);
        $orderArr  = $postArr[2];
        $orderInfo = explode("=", $orderArr);
        $orderId   = $orderInfo[1];

        $service = new PaymentService;
        $service->setOrderId($orderId);
        $service->wechatRefound();

        $this->logger->log('退改通知'.$testData);

        header("Content-type:text/xml;charset=utf-8");
        echo '<?xml version="1.0" encoding="UTF-8"?><root><result>true</result><msg>接收成功</msg></root>';
        exit;
    }






}
